<template>
  <el-row style="min-width: 1500px">
    <el-col :span="24">
      <div class="program_flex_box x-flex">
        <div class="wrap_right_list">
          <div class="wrap_right_list--head-title">
            <text>角色列表</text>
          </div>
          <div class="wrap_right_list--head-operation x-scroll">
            <div class="x-flex">
              <div class="x-m-r-12">
                <el-button
                  size="large"
                  style="
                    color: #fff;
                    border-color: #0daeff;
                    background-color: #0daeff;
                  "
                  @click="onEquipInfo('1')"
                  v-has="'Addrole'"
                  >新增角色</el-button
                >
                <!-- 新增角色弹框 -->
                <el-dialog
                  v-model="dialogFormVisibles"
                  width="70%"
                  @close="closeClick"
                >
                  <template #header="{ titleId, titleClass }">
                    <div class="my-header">
                      <h4
                        :id="titleId"
                        :class="titleClass"
                        style="display: flex; align-items: center"
                      >
                        <div class="add"></div>
                        <div style="margin: 0 5px">{{ title }}</div>
                      </h4>
                    </div>
                  </template>
                  <div style="display: flex; align-items: center">
                    <span style="margin: 0 10px">角色名称 </span>
                    <el-input
                      style="width: 200px; align-items: center"
                      v-model="roseInput"
                      :disabled="disabledd"
                    ></el-input>
                  </div>
                  <div class="e-l-dialog_box">
                    <div class="x-flex x-row-between x-m-b-20">
                      <div style="margin: 10px 0">
                        <el-menu
                          :default-active="infoEquipCount"
                          :ellipsis="false"
                          class="el-menu-demo"
                          mode="horizontal"
                          @select="Onselect"
                          style="display: flex"
                        >
                          <el-menu-item index="1">PC端</el-menu-item>
                          <el-menu-item index="2">小程序</el-menu-item>
                        </el-menu>
                      </div>
                    </div>
                  </div>
                  <div v-show="infoEquipCount == '1'">
                    <el-tree
                      :data="roleData"
                      :show-checkbox="disableCheckbox"
                      node-key="value"
                      :props="defaultProps"
                      :check-strictly="strictly"
                      :default-expanded-keys="keys"
                      :default-checked-keys="keys"
                      @check-change="checkChang"
                      default-expand-all
                      ref="treeRef"
                    />
                  </div>
                  <div v-show="infoEquipCount == '2'">
                    <el-tree
                      :data="roleDatas"
                      default-expand-all
                      :show-checkbox="disableCheckbox"
                      node-key="value"
                      :default-expanded-keys="keys"
                      :props="defaultProps"
                    />
                  </div>
                  <template #footer>
                    <span class="dialog-footer">
                      <el-button @click="close">取消</el-button>
                      <el-button type="primary" @click="openRole">
                        确定
                      </el-button>
                    </span>
                  </template>
                </el-dialog>
              </div>
            </div>
          </div>
          <div
            v-show="AdvancedSearchShow"
            style="margin-bottom: 16px !important"
            class="-advancedInput x-flex"
          >
            <div class="-addDialogFormInput e-l-cascader">
              <el-select
                v-model="equipForm.role"
                class="x-m-r-12"
                style="width: 10.6vw"
                ref="regionRefs"
                placeholder="请选择角色"
                size="large"
              >
                <el-option
                  v-for="item in treesd"
                  :label="item.label"
                  :value="item.value"
                  @click="roleClick(item.value)"
                />
              </el-select>
            </div>
            <el-select
              v-model="equipForm.Status"
              class="x-m-r-12"
              style="width: 10.6vw"
              placeholder="请选择播放状态"
              size="large"
            >
              <el-option label="已启用" @click="addElemt" value="0" />
              <el-option label="已暂停" @click="addElemts" value="1" />
            </el-select>
            <div></div>
            <el-button size="large" @click.stop="onCancel">
              <el-icon>
                <RefreshLeft />
              </el-icon>
            </el-button>
          </div>
          <div class="wrap_right_list--table-content">
            <el-table
              ref="multipleTableRef"
              :data="tableData"
              :header-cell-style="{ background: '#F6F7F9' }"
              :row-style="{ height: '64px' }"
              height="calc(90vh - 220px)"
              style="width: 100%; z-index: 1"
              @selection-change="handleSelectionChange"
            >
              <template #empty>
                <div class="no-data">
                  <el-empty
                    :image="require('../../assets/nothave.png')"
                    style="margin-top: 30%"
                  >
                  </el-empty>
                </div>
              </template>
              <el-table-column type="selection" />
              <el-table-column
                label="角色名称"
                property="roleName"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column label="用户数量">
                <template #default="{ row }">
                  <div v-if="row.linkSum">
                    {{ row.linkSum }}
                  </div>
                  <div v-else>-</div>
                </template>
              </el-table-column>

              <el-table-column label="创建用户" property="createdAccount" />

              <el-table-column
                label="操作"
                style="display: flex; align-items: center"
              >
                <template #default="{ row }">
                  <div style="display: flex; align-items: center">
                    <el-button
                      size="small"
                      text
                      type="primary"
                      @click="copyTableObj(row)"
                      style="margin: 0 -10px"
                      v-has="'AddrolExamine'"
                      >查看
                    </el-button>
                    <el-button
                      size="small"
                      text
                      @click="editclick(row)"
                      type="primary"
                      v-has="'roleEdit'"
                      v-if="row.roleRank"
                      >编辑
                    </el-button>
                    <el-button
                      size="small"
                      text
                      v-if="row.roleRank"
                      type="primary"
                      v-has="'roleDelete'"
                      @click="copyTableObjs(row.id)"
                      >删除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <div class="-pages">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 30, 40]"
                :total="total"
                background
                layout="total, sizes, prev, pager, next"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </div>
      </div>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import {
  onMounted,
  reactive,
  ref,
  shallowRef,
  watch,
  getCurrentInstance,
} from "vue";
import { RefreshLeft } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage, ElTable, ElMessageBox } from "element-plus";

import {
  structure,
  rolePage,
  roleLink,
  GetsysMenu,
  DelectProgramMenu,
  GetOpensysMenu,
  AllsysMenu,
} from "@/api/userManagement/index";
import { convertDatads, convertDatade, convertDataA } from "@/utils/list";

//新增分组
const dialogVisible = shallowRef(false);
const addTreeName = shallowRef("");
const TreeValue = ref(0);
// 新增子账户

const instance: any = getCurrentInstance();
//树形控件
const trees = ref<Tree[] | null>(null);
const treesd = ref<Tree[] | null>(null);
// 暂停/启用按钮状态

const dialogFormVisibles = ref(false);

const formInline = reactive({
  programName: "",
  programType: "",
  programResolution: "",
  programCustom: "", //自定义宽高
  wide: "", //宽
  High: "", //高
});
watch(
  () => formInline,
  (newVal) => {
    if (newVal.wide || newVal.High) {
      formInline.programCustom = `${newVal.wide}x${newVal.High}`;
    } else {
      formInline.programCustom = "";
    }
  },
  { deep: true }
);
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  programName: [{ required: true, message: "请填写节目名称", trigger: "blur" }],
  programType: [{ required: true, message: "请选择类型", trigger: "change" }],
  programResolution: [
    { required: true, message: "请选择分辨率", trigger: "change" },
  ],
  programCustom: [{ required: true, message: "请输入宽高", trigger: "blur" }],
});
// 清除搜索框
const onCancel = () => {
  for (let key in equipForm) {
    equipForm[key] = "";
  }
  userId.value = "";
  paging();
};
const roleClick = (val: any) => {
  equipForm.role = val;
  paging();
};
var userId = ref("");
const addElemt = () => {
  userId.value = "0";
  paging();
};
const addElemts = () => {
  userId.value = "1";
  paging();
};

// 新增角色数据
const roleData = ref();
const roleDatas = ref();
const options = shallowRef([]);
const activeName = ref("first");
const infoEquipCount = shallowRef("1");
const radioControl = ref("xinfa");
const disabledd = ref(false);
var strictly = ref(true);
//新增角色弹框按钮
const onEquipInfo = async (num: string | number) => {
  disableCheckbox.value = true;
  disabledd.value = false;
  radioControl.value = "xinfa";
  dialogFormVisibles.value = true;
  num == "1" ? (infoEquipCount.value = "1") : (infoEquipCount.value = "2");
  sysMenus();
};
const sysMenus = async () => {
  let data = {
    linkSystem: radioControl.value,
  };
  let res = await AllsysMenu(data);
  roleData.value = convertDataA(res.data.data);
};
// 获取菜单列表
const Onselect = async (vals: any) => {
  infoEquipCount.value = vals;
  let val = ref(vals);
  if (val.value == "1") {
    radioControl.value = "xinfa";
    let data = {
      linkSystem: radioControl.value,
    };
    let res = await AllsysMenu(data);
    roleData.value = convertDataA(res.data.data);
  } else if (val.value == "2") {
    let data = {
      linkSystem: (radioControl.value = "xinfaXcx"),
    };
    let res = await AllsysMenu(data);
    roleDatas.value = convertDataA(res.data.data);
  }
};
const roseInput = ref("");
const valId = ref([]);
var roleIds = ref("");
var treeRef = ref();
// 新增角色接口
const openRole = async () => {
  const treeInstance = treeRef.value; // 获取el-tree组件实例
  const checkedNodes = treeInstance.getCheckedNodes(); // 获取选中的节点数组
  const indeterminateNodes = treeInstance.getHalfCheckedNodes(); // 获取半选中的节点数组
  const checkedIds = ref();
  // 提取选中和半选中节点的ID
  if (checkedNodes) {
    checkedIds.value = checkedNodes.map((node: { value: any }) => node.value);
    const indeterminateIds = indeterminateNodes.map(
      (node: { value: any }) => node.value
    );
    valId.value = checkedIds.value + "," + indeterminateIds;
  } else {
    valId.value = checkedIds.value;
  }

  roseInput.value;
  if (!roseInput.value) {
    ElMessage({ message: "请输入角色名称", type: "error", duration: 1000 });
    return;
  }
  let data = {
    menuIds: valId.value
      .trim()
      .split(",")
      .filter((item: string) => item !== ""),
    roleId: roleIds.value,
    roleName: roseInput.value,
    linkSystem: "xinfa",
    pid: "",
  };
  let res = await roleLink(data);
  if (res.data.code == 1) {
    paging();
    dialogFormVisibles.value = false;
    ElMessage({ message: res.data.msg, type: "success", duration: 1000 });
    if (roleIds) {
      keys.value = "";
    }
  } else {
    ElMessage({ message: res.data.msg, type: "error", duration: 1000 });
  }
};
const keys = ref<any>([]);
const checkChang = (val: any) => {
  if (val) {
    strictly.value = false;
  }
};
// 角色编辑按钮
const editclick = async (row: any) => {
  title.value = "编辑角色";
  disableCheckbox.value = true;
  strictly.value = true;
  disabledd.value = false;
  roseInput.value = row.roleName;
  roleIds.value = row.id;
  sysMenus();
  dialogFormVisibles.value = true;
  let data = await GetOpensysMenu(row.id);
  let result = convertDataA(data.data.data);
  const getIds = (result: any[]) => {
    const ids: any[] = [];

    const traverse = (item: { value: any; children: any[] }) => {
      ids.push(item.value);

      if (item.children && item.children.length > 0) {
        item.children.forEach((child: any) => {
          traverse(child);
        });
      }
    };

    result.forEach((item: any) => {
      traverse(item);
    });

    return ids;
  };
  keys.value = [getIds(result)].flat();
};
var disableCheckbox = ref(false);
// 新增角色props配置
const defaultProps = ref({
  children: "children",
  label: "label",
});
// 取消按钮
const close = () => {
  dialogFormVisibles.value = false;
  roleIds.value = "";
  roseInput.value = "";
  keys.value = "";
};
var title = ref("新增角色");
const closeClick = () => {
  title.value = "新增角色";
  dialogFormVisibles.value = false;
  roleIds.value = "";
  roseInput.value = "";
  keys.value = "";
};

//表格数据
var tableData: any = ref([]);
// 获取用户分组列表
const getTreeData = async () => {
  const { data } = await structure();
  if (data.code !== 1)
    return ElMessage({ message: data.msg, type: "error", duration: 1000 });
  trees.value = convertDatads(data.data);
};

//表单部分
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<programMsgTable[]>([]);
const id = ref([]);
var list = ref();
//勾选表单时触发
const handleSelectionChange = (val: programMsgTable[]) => {
  list.value = JSON.parse(JSON.stringify(val));

  id.value = list.value.map((a: { id: any }) => a.id);
  multipleSelection.value = val;
};

const equipForm = reactive<TscEquip>({
  eNo: "",
  eName: "",
  eEquipName: [],
  role: [],
  eResponsible: "",
  eRegion: [],
  pas: "",
  Version: "",
  ids: "",
  Status: "",
});
const equipRules = reactive<FormRules>({
  eNo: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        const reg = /^[^\u4e00-\u9fff]*$/;
        // eslint-disable-next-line no-console
        if (!reg.test(equipForm.eNo)) {
          callback(new Error("不能输入中文格式的用户名,请重新输入"));
        } else {
          callback();
        }
      },
    },
  ],
  eName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  pas: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        const reg = /^[A-Z].{5,14}$/;
        // eslint-disable-next-line no-console
        if (!reg.test(equipForm.pas)) {
          callback(new Error("输入的密码格式不正确或者长度不够6位,请重新输入"));
        } else {
          callback();
        }
      },
    },
  ],
  eEquipName: [{ required: true, message: "请选择分组", trigger: "blur" }],
  role: [{ required: true, message: "请选择角色", trigger: "blur" }],
  eResponsible: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
        // eslint-disable-next-line no-console
        if (!reg.test(equipForm.eResponsible)) {
          callback(new Error("输入的手机号不正确,请重新输入"));
        } else {
          callback();
        }
      },
    },
  ],
  eRegion: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        const reg = /^[\w.-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        // eslint-disable-next-line no-console
        if (!reg.test(equipForm.eRegion)) {
          callback(new Error("输入的邮箱不正确,请重新输入"));
        } else {
          callback();
        }
      },
    },
  ],
});

var regionRefs = ref();

const isNewDevice = shallowRef(false);

// 高级搜索显示隐藏
const AdvancedSearchShow = shallowRef(false);

//查看
const copyTableObj = async (row: any) => {
  title.value = "查看角色";
  dialogFormVisibles.value = true;
  disableCheckbox.value = false;
  disabledd.value = true;
  roseInput.value = row.roleName;
  roleIds.value = row.id;
  sysMenus();
  dialogFormVisibles.value = true;
  let data = await GetOpensysMenu(row.id);
  let result = convertDataA(data.data.data);
  keys.value = result.map((item: any) => {
    return item.value;
  });
};
// 删除
const copyTableObjs = async (id: any) => {
  ElMessageBox.confirm("删除的角色不支持找回，确定要删除当前角色吗?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let res = await DelectProgramMenu(id);
      if (res.data.code == 1) {
        paging();
        ElMessage({ message: res.data.msg, type: "success", duration: 1000 });
      } else if (res.data.code == 0) {
        ElMessage({ message: res.data.msg, type: "error", duration: 1000 });
      } else {
        ElMessage({ message: res.data.msg, type: "error", duration: 1000 });
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

//分页
const currentPage = ref(1);
const pageSize = ref(10);

var total = ref();

const searchInput = ref("");

const paging = async () => {
  let data = {
    // pageNum: currentPage.value,
    // pageSize: pageSize.value,
    linkSystem: "xinfa",
  };
  let res = await GetsysMenu(data);

  if (res.data.code == 0) {
    ElMessage({ message: res.data.msg, type: "error", duration: 1000 });
    return;
  }
  tableData.value = res.data.data;
  total = res.data.data;
};
//pages
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  paging();
};
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  paging();
};
onMounted(async () => {
  setTimeout(() => {
    // 加载完成后设置 isLoading 为 false
    strictly.value = false;
  }, 2000);
  getTreeData();
  const res = await rolePage();
  treesd.value = convertDatade(res.data.data);

  getTreeData();
  paging();
});
</script>
<style lang="scss" scoped>
.-addEquip_minHead {
  font-weight: 700;
}
::v-deep .el-input input::selection {
  background-color: #79bbff;
}
.add {
  width: 3px;
  height: 20px;

  /* 主色 */

  background: #0daeff;
  border-radius: 3px;

  /* Inside auto layout */

  flex: none;
  order: 0;
  flex-grow: 0;
}
::v-deep .wrap_right_list--table-content .el-dropdown-link[data-v-7443f3dc] {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
  font-size: 12px;
  margin-left: 12px;
  padding: 7px 11px;
  outline: none;
}
.program_flex_box {
  width: 100%;
  height: calc(100vh - 100px);
  font-size: 14px;
}
.wrap_left_grouping {
  width: 20%;
  height: 100%;
  background-color: white;
  border-radius: 10px;
  padding: 15px;
  color: #303233;
  overflow-y: auto;

  &--head-title {
    height: 56px;
    line-height: 56px;
    border-bottom: 1px solid #f6f7f9;
    white-space: nowrap;
    font-weight: 500;
  }

  &--content-area {
    padding: 20px 5px;

    .edit-child-node {
      width: calc(100% - 10px);
      height: 26px;

      :deep(.el-input__wrapper) {
        background: rgba(255, 255, 255, 0.6);
      }
    }
  }
}
.e-l-dialog_box {
  width: 100%;
  padding: 0 20px;
  overflow: hidden;

  .control_prompt {
    font-weight: 500;
    margin-bottom: 20px;
  }

  .control_content {
    font-weight: 400;
  }

  :deep(.el-menu--horizontal) {
    border-bottom-width: 0;
  }

  .el-menu-demo {
    height: 30px;
  }
}
.wrap_right_list {
  width: 100%;
  height: 100%;
  background-color: white;
  border-radius: 10px;
  padding: 15px;
  // margin-left: 10px;
  overflow: hidden;
  position: relative;

  &--head-title {
    height: 56px;
    line-height: 56px;
    border-bottom: 1px solid #f6f7f9;
    white-space: nowrap;
    font-weight: 500;
  }

  &--head-operation {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    padding: 20px 0;
    overflow: hidden;

    &:hover {
      overflow-x: auto;
    }

    .-row--search {
      display: grid;
      grid-template-areas: "a b c";
    }

    .-dialog-input {
      width: 100%;
      overflow: hidden;

      :deep(.el-form-item__content) {
        max-width: 450px;
      }

      :deep(.el-select) {
        width: 450px;
      }

      .-addDialogFormInput {
        :deep(.el-input) {
          max-width: 190px;
        }
      }
    }
  }

  &--table-content {
    .el-dropdown-link {
      cursor: pointer;
      color: var(--el-color-primary);
      display: flex;
      align-items: center;
      font-size: 12px;
      margin-left: 12px;
      padding: 5 px 11px;
      outline: none;
    }

    .file-child-node {
      width: calc(100% - 40px);
      height: 26px;
    }

    :deep(.el-table__row):hover .--table-column-icon {
      display: inline-block;
    }

    .--table-column-icon {
      display: none;
      margin-left: 10px;
      cursor: pointer;

      &:hover {
        :deep(.el-icon) {
          color: var(--el-color-primary);
        }
      }
    }

    .-pages {
      position: absolute;
      left: 50%;
      bottom: 20px;
      transform: translateX(-50%);
    }

    :deep(.is-background .btn-prev) {
      border: 1px solid var(--el-border-color);
      background-color: var(--el-input-bg-color, var(--el-fill-color-blank));
    }

    :deep(.is-background .btn-next) {
      border: 1px solid var(--el-border-color);
      background-color: var(--el-input-bg-color, var(--el-fill-color-blank));
    }

    :deep(.el-pager li) {
      border: 1px solid var(--el-border-color);
      background-color: var(--el-input-bg-color, var(--el-fill-color-blank));
    }
  }
}
</style>
